package cn.edu.ujs.coor.service;

import cn.edu.ujs.coor.repository.BaseMapper;
import cn.edu.ujs.coor.request.PageRequest;
import cn.edu.ujs.coor.response.PageResponse;
import com.github.pagehelper.Page;
import lombok.Data;
import org.apache.ibatis.session.RowBounds;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
import java.util.Optional;

@Data
public class BaseService<T, R> {
    protected BaseMapper<R> mapper;

    protected JpaRepository repository;

    public PageResponse<R> page (PageRequest request) {
        Page<R> result = mapper.page(request, new RowBounds(request.getIndex(), request.getSize()));
        return new PageResponse<R>(result.getResult(), request, result.getTotal());
    }

    public T findById (Object id) {
        Optional<T> optional = repository.findById(id);
        return optional.orElse(null);
    }

    public List<T> findAll () {
        return repository.findAll();
    }

    public void save (T t) {
        repository.save(t);
    }

    public void delete (T t) {
        repository.delete(t);
    }

    public void deleteById (Object id) {
        repository.deleteById(id);
    }
}
